package com.y.fund.handler;

import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.y.fund.aacore.data.DataVo;
import com.y.fund.utils.StrUtil;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ResponseBody
	@ExceptionHandler(value =NullPointerException.class)
	public DataVo nullExceptionHandler(NullPointerException e){
    	String msg = e.getMessage();
    	if(StrUtil.isBlankIncNullStr(msg)) {
    		msg = "Required data is blank, please improve!";
    	}
		DataVo dv = DataVo.FailMustParam(msg);
		dv.setData(e.getStackTrace()[0]);
		e.printStackTrace();
       	return dv;
    }
    
    @ResponseBody
	@ExceptionHandler(value =Exception.class)
	public DataVo exceptionHandler(Exception e){
    	String msg = e.getMessage();
    	if(StrUtil.isBlankIncNullStr(msg)) {
    		msg = "Unable to process data, please check the log and modify!";
    	}else if(msg.contains("Required request parameter")) {
    		msg = "有必填参数没有输入! 异常信息为：" + msg;
    	}
		DataVo dv = DataVo.Fail(msg);
		dv.setData(e.getStackTrace()[0]);
		e.printStackTrace();
       	return dv;
    }

	@ResponseBody
	@ExceptionHandler(value = MethodArgumentNotValidException.class)
	public DataVo validatedExceptionHandler(MethodArgumentNotValidException e) {
		BindingResult bindingResult = e.getBindingResult();
		StringBuilder builder = new StringBuilder();
		bindingResult.getFieldErrors().forEach(fieldError ->
				builder.append(fieldError.getDefaultMessage())
						.append("(").append(fieldError.getField()).append(")")
						.append("，"));
		DataVo dv = DataVo.Fail("数据校验异常");
		dv.setData(builder.deleteCharAt(builder.length() -1 ).toString());
		return dv;
	}
}
